#ifndef AI_CHATBOT_H
#define AI_CHATBOT_H

#include <Arduino.h>
#include <ArduinoJson.h>

#if defined(ESP32)
  #include <WiFi.h>
  #include <WiFiClientSecure.h>
  #include <HTTPClient.h>
  #define PLATFORM_NAME "ESP32"
#elif defined(ESP8266)
  #include <ESP8266WiFi.h>
  #include <ESP8266HTTPClient.h>
  #define PLATFORM_NAME "ESP8266"
#endif


#define AI_CHATBOT_CHAT_GPT_URL "https://api.openai.com/v1/chat/completions"
#define AI_CHATBOT_HUGGING_FACE_URL "https://api-inference.huggingface.co/models/"
#define AI_CHATBOT_DEEP_SEEK_URL "https://api.deepseek.com/chat/completions"
#define AI_CHATBOT_SILICON_FLOW_URL "https://api.siliconflow.cn/v1/chat/completions"
#define AI_CHATBOT_VOLC_ENGINE_URL "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
#define AI_CHATBOT_LING_YI_WAN_WU_URL "https://api.lingyiwanwu.com/v1/chat/completions"
#define AI_CHATBOT_MOON_SHOT_URL "https://api.moonshot.cn/v1/chat/completions"
#define AI_CHATBOT_BAI_CHUAN_AI_URL "https://api.baichuan-ai.com/v1/chat/completions"
#define AI_CHATBOT_TENCENT_HUN_YUAN_URL "https://api.hunyuan.cloud.tencent.com/v1/chat/completions"
#define AI_CHATBOT_ALIYUN_BAI_LIAN_URL "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"


class AIChatbot {
public:
    AIChatbot();
    AIChatbot(const String& key, const String& ai);
    AIChatbot(const String& key, const String& ai, const String& message);
    void setKey(const String& key);
    void setTimeout(uint16_t timeout = 10000);
    void setMaxRetries(uint8_t maxRetries = 1);
    void setSystemPrompt(const String& message);
    void setCustomUrl(const String& url);
    void selectAI(const String& ai);
    void selectAI(const String& aiName, const String& aiVersion);
    void enableHistoryMessages(bool state);
    void setHistoryMessagesNum(uint8_t num);
    void emptyHistoryMessages();
    void addHistoryMessage(const String& role, const String& content);
    void clearUserHistoryMessages();
    String chat(const String& message, uint16_t maxTokens = 1024, void (*contentCallback)(String) = NULL, void (*reasoningContentCallback)(String) = NULL);

private:
    String _apiKey;
    String _url;
    String _selectedAI;
    String _selectedAIVersion;
    String _info;
    bool _history = false;
    uint8_t _maxHistoryNum = 3;
    uint16_t _timeout = 10000;
    uint8_t _maxRetries = 1;
    JsonDocument _doc;
    JsonArray _messages = _doc.to<JsonArray>();
    bool validateKeys();
    String sendToCommonGPT(const String& url, const String& message, uint16_t maxTokens, void (*contentCallback)(String) = NULL, void (*reasoningContentCallback)(String) = NULL);
    String sendToHuggingFace(const String& message, uint16_t maxTokens, void (*contentCallback)(String) = NULL, void (*reasoningContentCallback)(String) = NULL);
    String makeHttpRequest(const String& url, const String& payload, const String& apiKey, void (*contentCallback)(String) = NULL, void (*reasoningContentCallback)(String) = NULL);
};

#endif // AI_CHATBOT_H